#!/usr/bin/env python3

import hashlib
import json
import os

class literature:
    def __init__(self, filePath):
        self.literature_filePath = filePath
        self.literature_filename = filePath.split("/")[-1]
        self.literature_sign = self.__getMD5File(filePath)
        self.literature_keys = []
        self.literature_authors = []
        self.literature_abstract = ""
        from literatureTool.config import config
        cf = config.config()
        self.literature_dataPath = os.path.join(cf.literatures_DB_directory , self.literature_sign+".json")
        self.literature_readHistory = []
        self.literature_isread = 0

    def __getMD5File(self, filePath):
        file = open(filePath, "rb")
        md5 = hashlib.md5()
        md5.update(file.read())
        file.close()
        #print(md5.hexdigest())
        return md5.hexdigest()

    def addKey(self, key):
        if key not in self.literature_keys:
            self.literature_keys.append(key)

    def addAuthor(self, author):
        if author not in self.literature_authors:
            self.literature_authors.append(author)

    def updateAbstract(self, abstract):
        self.literature_abstract = abstract

    def saveLiteratureData(self):
        f = open(self.literature_dataPath, "w")
        s = json.dumps(self, cls=literatureEncoder, indent=4)
        f.write(s)
        f.close()

    def addReadHistory(self, time):
        self.literature_isread = 1
        self.literature_readHistory.append(time)

    def unset_literature_unread(self):
        self.literature_readHistory = []
        self.literature_isread = 0

    def literation_info(self):
        print("FilePath: ", self.literature_filePath)
        print("FileName: ", self.literature_filename)
        print("LiterationSign: ", self.literature_sign)
        print("LiterationAuthors: ", self.literature_authors)
        print("LiterationKeys: ", self.literature_keys)
        print("LiterationAbstract: ", self.literature_abstract)
        print("LiterationDataPath: ", self.literature_dataPath)
        print("LiterationReadHistory: ", self.literature_readHistory)
        print("LiterationIsRead: ", self.literature_isread)

def loadLiteratureFromDataFile(dataFile):
        f = open(dataFile, "r")
        s = f.read()
        f.close()
        return json.loads(s, object_hook=as_literature)


class literatureEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, literature):
            ret = {}
            ret['literature_filePath'] = obj.literature_filePath
            ret['literature_filename'] = obj.literature_filename
            ret['literature_sign'] = obj.literature_sign
            ret['literature_keys'] = obj.literature_keys
            ret['literature_authors'] = obj.literature_authors
            ret['literature_abstract'] = obj.literature_abstract
            ret['literature_dataPath'] = obj.literature_dataPath
            ret['literature_readHistory'] = obj.literature_readHistory
            ret['literature_isread'] = obj.literature_isread
            return ret
        return json.JSONEncoder.default(self, obj)


def as_literature(dct):
    if os.path.exists(dct['literature_filePath']):
        ret = literature(dct['literature_filePath'])
        for key in dct['literature_keys']:
            ret.addKey(key)
        for author in dct['literature_authors']:
            ret.addAuthor(author)
        ret.updateAbstract(dct['literature_abstract'])
        ret.literature_dataPath = dct['literature_dataPath']
        ret.literature_readHistory = dct['literature_readHistory']
        ret.literature_isread = dct['literature_isread']
        return ret
    else:
        return None


def test():
    li = "/home/archlinux/Practice/literatureTool/literature/xyz.pdf"
    a = literature(li)
    a.addKey("lithium")
    a.addKey("oxgen")
    a.addAuthor("wangxinglong")
    a.updateAbstract("wo update lithium oxgen.")
    print("literature_filePath: ",a.literature_filePath)
    print("literature_filename: ",a.literature_filename)
    print("literature sign: ",a.literature_sign)
    print("literature keys: ", a.literature_keys)
    print("literature authors: ", a.literature_authors)
    print("literature abstract: ", a.literature_abstract)
    print("literature data: ", a.literature_dataPath)
    a.saveLiteratureData()
    b = loadLiteratureFromDataFile(a.literature_dataPath)
    print()
    print("----------------------------------------------------------------------")
    print("literature_filePath: ",b.literature_filePath)
    print("literature_filename: ",b.literature_filename)
    print("literature sign: ",b.literature_sign)
    print("literature keys: ", b.literature_keys)
    print("literature authors: ", b.literature_authors)
    print("literature abstract: ", b.literature_abstract)
    print("literature data: ", b.literature_dataPath)

if __name__ == "__main__":
    test()
